import { _decorator, Collider2D, Contact2DType, IPhysics2DContact } from 'cc';
import { BaseSkill } from './BaseSkill';
import { CharacterController } from '../controllers/CharacterController';
import { EvolutionSkills } from '../config/EvolutionConfig';
import { GameTags } from '../constants/GameConstants';

const { ccclass, property } = _decorator;

@ccclass('SwimSkill')
export class SwimSkill extends BaseSkill {
    @property(CharacterController)
    private characterController: CharacterController | null = null;

    @property(Collider2D)
    private collider: Collider2D | null = null;

    private isInWater: boolean = false;
    private oxygenTimer: number = 0;
    private readonly waterSpeedBoost: number = EvolutionSkills.swim.waterSpeedBoost;
    private readonly maxOxygenTime: number = EvolutionSkills.swim.oxygenTime;
    private originalSpeed: number = 0;

    start() {
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onWaterEnter, this);
            this.collider.on(Contact2DType.END_CONTACT, this.onWaterExit, this);
        }
    }

    update(deltaTime: number) {
        super.update(deltaTime);
        this.updateOxygen(deltaTime);
    }

    private updateOxygen(deltaTime: number) {
        if (this.isInWater && !this.isActive) {
            this.oxygenTimer += deltaTime;
            if (this.oxygenTimer >= this.maxOxygenTime) {
                // 溺水伤害
                const player = this.node.getComponent('Player');
                if (player) {
                    player.takeDamage(10 * deltaTime);
                }
            }
        }
    }

    private onWaterEnter(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.tag === GameTags.WATER) {
            this.isInWater = true;
            this.use(); // 自动激活游泳能力
        }
    }

    private onWaterExit(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
        if (otherCollider.tag === GameTags.WATER) {
            this.isInWater = false;
            this.deactivate();
            this.oxygenTimer = 0;
        }
    }

    protected onActivate(): void {
        if (!this.characterController || !this.isInWater) return;

        this.originalSpeed = this.characterController.moveSpeed;
        this.characterController.moveSpeed *= this.waterSpeedBoost;
    }

    protected onDeactivate(): void {
        if (!this.characterController) return;
        
        this.characterController.moveSpeed = this.originalSpeed;
    }

    onDestroy() {
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onWaterEnter, this);
            this.collider.off(Contact2DType.END_CONTACT, this.onWaterExit, this);
        }
    }
} 